import React, {PureComponent} from "react";
import {hidePartExport, updateRateDataSource} from "./actions";
import {connect} from "react-redux";
import {Form, InputNumber, Modal, notification, Select, Table} from "antd";
import {getPrincipal} from "../../lib/identity";
import {Resizable} from 'react-resizable';
import {formItemLayout, tableProps} from "../../lib/ui";
import {partExportByType3} from "../ghOrderPayable/actions";

const {Option} = Select;

const ResizeableTitle = props => {
    const {onResize, width, ...restProps} = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{enableUserSelectHack: false}}
        >
            <th {...restProps} />
        </Resizable>
    );
};

class PartExportModal extends PureComponent {

    state = {'currency': "", 'selectId': "", bankInfoId: undefined};
    handleExport = () => {
        const {form: {validateFields}, dispatch, ids, rateData} = this.props;
        const bankInfoId = this.state.bankInfoId;
        if (bankInfoId === null || bankInfoId === undefined || bankInfoId.length === 0) {
            notification.error({
                message: '请选择银行账号信息'
            });
            return;
        }
        const currency = this.state.currency;
        if("无需转换" !== currency){
            // 如果选了币种，需要判断币种列表是否大于0
            if(rateData === undefined || rateData === null || rateData.length === 0){
                notification.error({
                    message: '请先维护一条符合日期有效期范围的汇率再进行操作'
                });
                return;
            }
        }
        validateFields((err, values) => {
            if (!err) {
                const exportData = {
                    ids: ids,
                    bankInfoId: bankInfoId,
                    tableName: "ghOrderReceivable",
                    rateList: rateData,
                    type: "IN",
                    currency: currency,
                    userId: getPrincipal().id
                };
                dispatch(partExportByType3(exportData)).then(action => {
                    if (action.error !== true) {
                        const fileName = action.payload;
                        dispatch(hidePartExport());
                        window.location.href = "/file/" + fileName;
                    }
                });
            }
        });
    };

    handleCancel = () => {
        const {dispatch} = this.props;
        dispatch(hidePartExport());
    };

    handleSelectChange = value => {
        this.setState({'currency': value});
        const {dispatch, rateList, model} = this.props;
        model.currency = value;
        if ("无需转换" !== value) {
            const rateData = [];
            rateList.forEach(item => {
                if (item.fromRate === value || item.toRate === value) {
                    delete item.createTime;
                    delete item.startDate;
                    delete item.endDate;
                    rateData.push(item);
                }
            });
            dispatch(updateRateDataSource(rateData));
        } else {
            dispatch(updateRateDataSource([]));
        }
    };

    onChangeInvoiceDate = (value, dateString) => {
        document.getElementById("invoiceDate").value = dateString;
    };

    onChangeSettlementDate = (value, dateString) => {
        document.getElementById("settlementDate").value = dateString;
    };

    changeRemark = value => {
        document.getElementById("remark").value = value;
    };

    rowOnClick = record => {
        this.setState({'selectId': record.id});
    };

    onChange = value => {
        const {rateData} = this.props;
        const found = rateData.find(fee => fee.id === this.state.selectId);
        if (found) {
            found.rate = value;
        }
    };

    changeBank = value => {
        this.setState({bankInfoId: value});
    };

    components = {
        header: {
            cell: ResizeableTitle
        },
    };

    handleResize = index => (e, {size}) => {
        this.setState(({columns}) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return {columns: nextColumns};
        });
    };

    render() {
        const {ids, visible, rateData, loading, bankList, model, currencyList, form: {getFieldDecorator}} = this.props;

        const rateColumns = [
            {
                title: '转换前币种',
                dataIndex: 'fromRate',
                width: 100
            },
            {
                title: '转换后币种',
                dataIndex: 'toRate',
                width: 100
            },
            {
                title: '汇率',
                dataIndex: 'rate',
                width: 100,
                render: (text) => <InputNumber defaultValue={text} onChange={this.onChange}/>
            }
        ];


        const resizeColumns = rateColumns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));
        return (
            <Modal
                title="导出设置"
                visible={visible}
                onOk={this.handleExport}
                onCancel={this.handleCancel}
                confirmLoading={loading}
                okText="导出"
                cancelText="取消"
                width="40%"
            >
                <div style={{margin: 10}}>
                    选择币种：<Select
                    placeholder="请选择一种转换方式"
                    onChange={this.handleSelectChange}
                    style={{width: 180}}
                    value={this.state.currency}
                >
                    <Option value="无需转换">无需转换</Option>
                    {currencyList.map(item => (
                        <Option value={item.name} key={item.name}>
                            {item.name}
                        </Option>
                    ))}
                </Select>
                </div>
                {model.currency !== "无需转换" && rateData.length > 0 ?
                    <Table
                        {...tableProps}
                        components={this.components}
                        onRow={record => {
                            return {
                                onClick: event => {
                                    this.rowOnClick(record)
                                }, // 点击行
                            };
                        }}
                        rowClassName={() => 'editable-row'}
                        bordered
                        dataSource={rateData}
                        columns={resizeColumns}
                    /> : null}
                <div style={{margin: 10}}>
                    银行账号信息：<Select style={{width: 300}}
                                   placeholder="请选择银行账号信息"
                                   onChange={this.changeBank}
                >
                    {bankList.map(bank => (
                        <Option value={bank.id} key={bank.mark}>
                            {bank.mark + " 人民币账户" + bank.rmbAccount + " 美元账户" + bank.usdAccount}
                        </Option>
                    ))}
                </Select>
                </div>
                <form
                    id="partExportByType"
                    method="post"
                    target="_blank"
                    action="/api/ghOrder/partExportByType3"
                >

                    <input
                        name="userId"
                        type="hidden"
                        value={getPrincipal().id}
                    />
                    <input
                        name="type"
                        type="hidden"
                        value="IN"
                    />
                    <input
                        name="tableName"
                        type="hidden"
                        value="ghOrderReceivable"
                    />
                    <input
                        name="currencyType"
                        type="hidden"
                        value={this.state.currency}
                    />
                    <input
                        name="rateListStr"
                        type="hidden"
                        value={JSON.stringify(rateData)}
                    />
                    <input
                        name="ids"
                        type="hidden"
                        value={ids}
                    />
                    <input
                        id="invoiceDate"
                        name="invoiceDate"
                        type="hidden"
                    />
                    <input
                        id="settlementDate"
                        name="settlementDate"
                        type="hidden"
                    />
                    <input
                        id="remark"
                        name="remark"
                        type="hidden"
                    />
                    <input
                        id="bankInfoId"
                        name="bankInfoId"
                        type="hidden"
                    />
                </form>
            </Modal>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.ghOrderReceivable.partExport,
        rateList: state.ghOrderReceivable.list.rateList,
        currencyList: state.ghOrderReceivable.list.currencyList,
        bankList: state.bankInfo.list.dataSource
    };
};

const mapPropsToFields = ({model}) => {
    const fields = {};
    Object.keys(model).forEach(field => {
        fields[field] = Form.createFormField({value: model[field]});
    });
    return fields;
};

export default connect(mapStateToProps)(Form.create({mapPropsToFields})(PartExportModal));
